/***********************************************
 This file is part of redia-bapps-main-ios.
 
 Copyright (c) 2015 Redia A/S
 
 Redia-bapps-main-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-bapps-main-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-bapps-main-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

//
//  BAPatronReservationsViewController.m
//  redia-bapps-ios
//
//  Created by Henrik Lynbech on 27/08/13.
//  Copyright (c) 2013 redia. All rights reserved.
//

#import "BAPatronReservationsViewController.h"
#import "BAUtils.h"
#import "BAReservationCell.h"
#import "BABranch.h"
#import "BAReservation.h"
#import "BALibrarySettings.h"
#import "BAReservationReadyForPickupCell.h"
#import "BALoginViewController.h"

@interface BAPatronReservationsViewController ()

@end

@implementation BAPatronReservationsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(receivedBranchesListUpdated:)
                                                 name:BA_BRANCHES_LIST_UPDATED
                                               object:nil];
    branches = [BALibrarySettings instance].branches;
    [self buildBranchesDictionary:branches];

    //[self refreshReservationsList];
    [self setupCustomerColors:self];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setupCustomerColors:) name:BA_LIBRARY_SETTINGS_OBJECT_CHANGED object:nil];

}

/* deprecated
-(void)viewDidAppear:(BOOL)animated
{
    [[BALibrarySettings instance] fetchBranchesListIfNeeded];
}
*/

-(void)setupCustomerColors:(id)sender
{
    [self.deleteAllReservationsButton setTitleColor:[[BALibrarySettings instance] getCustomerColorNormal] forState:UIControlStateNormal];
}

-(void)dealloc
{
    [BARPCManager closeConnectionsForView:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:BA_LIBRARY_SETTINGS_OBJECT_CHANGED object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:BA_BRANCHES_LIST_UPDATED object:nil];
}


- (void)refreshReservationsList:(NSMutableArray*)list
{
    self.reservations = list;
    
    /* debugging test
    BAReservation* testres = [BAReservation new];
    testres.title=@"Hest";
    testres.pickUpBranch=@"ho";
    testres.pickUpNo=@"163";
    testres.pickUpExpireDate = [[NSDate dateWithTimeIntervalSinceNow:60*60*24*2] timeIntervalSince1970];
    testres.note=@"res note";
    testres.isReady=YES;
    testres.creators=@[@"The farmers"];
    [self.reservations addObject:testres];
     */
    
    [self.loadingIndicator stopAnimating];
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.reservations.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (RD_IS_IPAD) {
        return 100;
    } else {
        return 70;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    BAReservation* res = [self.reservations objectAtIndex:indexPath.row];
    DLog(@"Pick Up Expire Date: %d", res.pickUpExpireDate);
    if(res.pickUpExpireDate != -1) {
        BAReservationReadyForPickupCell* cell = [tableView dequeueReusableCellWithIdentifier:@"ReservationReadyForPickupCell"];
        if(cell == nil){
            if (RD_IS_IPAD) {
                cell = [[[NSBundle mainBundle] loadNibNamed:@"BAReservationReadyForPickupCell_iPad" owner:self options:nil] objectAtIndex:0];
            } else {
                cell = [[[NSBundle mainBundle] loadNibNamed:@"BAReservationReadyForPickupCell_iPhone" owner:self options:nil] objectAtIndex:0];
            }
            cell.parentReservationsController = self;
        }
        [cell setReservation:res];
        if(indexPath.row % 2 == 0) {
            [cell.contentView setBackgroundColor:[UIColor colorWithRed:241.0/255.0 green:241.0/255.0 blue:241.0/255.0 alpha:1]];
        } else {
            [cell.contentView setBackgroundColor:[UIColor colorWithRed:227.0/255.0 green:227.0/255.0 blue:227.0/255.0 alpha:1]];
        }
        return cell;
    } else {
        BAReservationCell* cell = [tableView dequeueReusableCellWithIdentifier:@"ReservationListCell"];
        if(cell == nil){
            if (RD_IS_IPAD) {
                cell = [[[NSBundle mainBundle] loadNibNamed:@"BAReservationCell_iPad" owner:self options:nil] objectAtIndex:0];
            } else {
                cell = [[[NSBundle mainBundle] loadNibNamed:@"BAReservationCell_iPhone" owner:self options:nil] objectAtIndex:0];
            }
            cell.parentReservationsController = self;
         }
        if(indexPath.row == 0) {
            [cell.gradientImageView setImage:[UIImage imageNamed:@"cell_left_gray_gradient_background_1"]];
        } else if (indexPath.row == 1) {
            [cell.gradientImageView setImage:[UIImage imageNamed:@"cell_left_gray_gradient_background_2"]];
        } else if (indexPath.row == 2) {
            [cell.gradientImageView setImage:[UIImage imageNamed:@"cell_left_gray_gradient_background_3"]];
        } else if (indexPath.row == 3) {
            [cell.gradientImageView setImage:[UIImage imageNamed:@"cell_left_gray_gradient_background_4"]];
        } else {
            [cell.gradientImageView setImage:[UIImage imageNamed:@"cell_left_gray_gradient_background_5"]];
        }
        
        [cell setReservation:res];
        
        if(indexPath.row % 2 == 0) {
            [cell.contentView setBackgroundColor:[UIColor colorWithRed:241.0/255.0 green:241.0/255.0 blue:241.0/255.0 alpha:1]];
        } else {
            [cell.contentView setBackgroundColor:[UIColor colorWithRed:227.0/255.0 green:227.0/255.0 blue:227.0/255.0 alpha:1]];
        }
            return cell;
    }

    


}

- (void)buildBranchesDictionary:(NSArray*)list {
    self.branchesDictionary = [[NSMutableDictionary alloc] init];
    for (BABranch* branch in branches) {
        [self.branchesDictionary setValue:branch.name forKey:branch.code];
    }
}

-(void)debugPrintResList:(NSArray*)resList preString:(NSString*)prependString
{
#ifdef DEBUG
    for (BAReservation* tempres in self.reservations) {
        DLog(@"%@: res rem id %@, adr %x", prependString, tempres.reservationRemoveId, (int) tempres);
    }
#endif
}

- (void)deleteReservation:(BAReservation *)reservation
{
    reservation.deleteReservationRpcPending = YES;
    [BALoginViewController checkLoginStatusFromViewController:self
                                                  resultBlock:^{
                                                      [BARPCManager removeReservationsAsyncFromView:self
                                                                                     reservationIds:@[reservation.reservationRemoveId]
                                                                                        resultBlock:^(id result) {
                                                                                            reservation.deleteReservationRpcPending=NO;
                                                                                        //FIXME: fejl: det retainede reservation object kan have en anden adresse end den i array'et
                                                                                            //DLog(@"rpc success on removing res rem id %@, adr %x",reservation.reservationRemoveId, (int)reservation);
                                                                                            //[self debugPrintResList:self.reservations preString:@"before"];
                                                                                            if ([self.reservations containsObject:reservation]) {
                                                                                                //DLog(@"res list did contain obj");
                                                                                                [self.tableView beginUpdates];
                                                                                                int index = [self.reservations indexOfObject:reservation];
                                                                                                NSIndexPath* ip = [NSIndexPath indexPathForRow:index inSection:0];
                                                                                                [self.tableView deleteRowsAtIndexPaths:@[ip] withRowAnimation:UITableViewRowAnimationLeft];
                                                                                                [self.reservations removeObject:reservation];
                                                                                                //[self debugPrintResList:self.reservations preString:@"after1"];
                                                                                                [self.tableView endUpdates];
                                                                                                //[self debugPrintResList:self.reservations preString:@"after2"];
                                                                                                [self.tableView reloadData];
                                                                                                //[self debugPrintResList:self.reservations preString:@"after3"];
                                                                                            } else {
                                                                                                DLog(@"warning: deleted reservation not found in reservations list, %@ %x", reservation.reservationRemoveId, (int) reservation);
                                                                                                //[self debugPrintResList:self.reservations preString:@"error didn't contain"];

                                                                                            }
                                                                                            [[NSNotificationCenter defaultCenter]
                                                                                             postNotificationName:BA_RESERVATION_RESERVATION_DELETED
                                                                                             object:self];
                                                                                        }
                                                                                         errorBlock:^(int errorCode, NSString *errorMessage) {
                                                                                             reservation.deleteReservationRpcPending=NO;
                                                                                             [self.tableView reloadData];
                                                                                             
                                                                                             UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Kunne ikke slette din reservering"
                                                                                                                                             message:errorMessage
                                                                                                                                            delegate:nil
                                                                                                                                   cancelButtonTitle:@"OK"
                                                                                                                                   otherButtonTitles:nil];
                                                                                             [alert show];
                                                                                             
                                                                                         }];
                                                  } errorBlock:^(int errorCode, NSString *errorMessage) {
                                                      reservation.deleteReservationRpcPending = NO;
                                                  }];
}

- (void) receivedBranchesListUpdated:(NSNotification*) notification
{
    DLog(@"receivedBranchesListUpdated");
    [self buildBranchesDictionary:branches];
    [self.tableView reloadData];
}


@end
